<template>
  <div class="resume-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">全局简历管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="fetchStatistics">
              <el-icon><Refresh /></el-icon>
              刷新统计
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计信息 -->
      <div class="statistics-section" v-loading="statisticsLoading">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.total_resumes }}</div>
                <div class="stat-label">总简历数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card pending">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.pending_reviews }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card approved">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.approved_resumes }}</div>
                <div class="stat-label">已通过</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card rejected">
              <div class="stat-content">
                <div class="stat-number">{{ statistics.rejected_resumes + statistics.needs_revision }}</div>
                <div class="stat-label">需修改</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
              <el-option label="待审核" value="pending_review" />
              <el-option label="已通过" value="approved" />
              <el-option label="未通过" value="rejected" />
              <el-option label="待修改" value="needs_revision" />
            </el-select>
          </el-form-item>
          <el-form-item label="学生姓名">
            <el-input v-model="filterForm.student_name" placeholder="输入学生姓名" clearable />
          </el-form-item>
          <el-form-item label="简历类型">
            <el-select v-model="filterForm.resume_type" placeholder="选择类型" clearable>
              <el-option label="在线生成" value="generated" />
              <el-option label="上传简历" value="uploaded" />
            </el-select>
          </el-form-item>
          <el-form-item label="指导老师">
            <el-select v-model="filterForm.advisor_id" placeholder="选择老师" clearable>
              <el-option 
                v-for="teacher in teacherList" 
                :key="teacher.id" 
                :label="teacher.username" 
                :value="teacher.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedResumeIds.length > 0">
        <el-alert
          :title="`已选择 ${selectedResumeIds.length} 个简历`"
          type="info"
          show-icon
          :closable="false"
        >
          <template #default>
            <div class="batch-buttons">
              <el-button type="success" size="small" @click="handleBatchUpdate('approved')">
                批量通过
              </el-button>
              <el-button type="warning" size="small" @click="handleBatchUpdate('needs_revision')">
                批量待修改
              </el-button>
              <el-button type="danger" size="small" @click="handleBatchUpdate('rejected')">
                批量拒绝
              </el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 简历列表 -->
      <div class="resume-list" v-loading="loading">
        <el-table
          :data="resumeList"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="title" label="简历标题" min-width="150" />
          <el-table-column prop="student_name" label="学生姓名" width="100" />
          <el-table-column prop="student_id" label="学号" width="120" />
          <el-table-column prop="advisor_name" label="指导老师" width="100" />
          <el-table-column prop="resume_type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.resume_type === 'uploaded' ? 'warning' : 'success'" size="small">
                {{ row.resume_type === 'uploaded' ? '上传' : '生成' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="completion_rate" label="完成度" width="100">
            <template #default="{ row }">
              <el-progress :percentage="row.completion_rate" :stroke-width="6" />
            </template>
          </el-table-column>
          <el-table-column prop="updated_at" label="更新时间" width="150">
            <template #default="{ row }">
              {{ formatTime(row.updated_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handlePreview(row)" plain>
                <el-icon><View /></el-icon>
                预览
              </el-button>
              <el-button type="success" size="small" @click="handleQuickReview(row)" plain>
                <el-icon><Check /></el-icon>
                快速审核
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 快速审核对话框 -->
    <el-dialog
      v-model="showQuickReviewDialog"
      title="快速审核"
      width="500px"
    >
      <el-form :model="quickReviewForm" label-width="100px">
        <el-form-item label="简历标题">
          <span>{{ currentResume?.title }}</span>
        </el-form-item>
        <el-form-item label="学生姓名">
          <span>{{ currentResume?.student_name }}</span>
        </el-form-item>
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="quickReviewForm.status">
            <el-radio value="approved">通过</el-radio>
            <el-radio value="needs_revision">待修改</el-radio>
            <el-radio value="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            v-model="quickReviewForm.comments"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showQuickReviewDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmQuickReview" :loading="reviewing">
          确定审核
        </el-button>
      </template>
    </el-dialog>

    <!-- 简历预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="`预览简历 - ${currentResume?.title}`"
      width="80%"
      top="5vh"
    >
      <EnhancedResumePreview
        v-if="currentResume && showPreviewDialog"
        :resume-id="currentResume.id"
        :file-url="currentResume.file_url"
        :file-name="currentResume.title"
        :title="currentResume.title"
      />
      <template #footer>
        <el-button @click="showPreviewDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Check } from '@element-plus/icons-vue'
import { resumeApi } from '@/api/resume'
import { formatTime } from '@/utils/format'
import EnhancedResumePreview from '@/components/EnhancedResumePreview.vue'

// 响应式数据
const loading = ref(false)
const statisticsLoading = ref(false)
const reviewing = ref(false)
const showQuickReviewDialog = ref(false)
const showPreviewDialog = ref(false)

const resumeList = ref([])
const teacherList = ref([])
const selectedResumeIds = ref<number[]>([])
const currentResume = ref(null)

const statistics = reactive({
  total_resumes: 0,
  pending_reviews: 0,
  approved_resumes: 0,
  rejected_resumes: 0,
  needs_revision: 0
})

const filterForm = reactive({
  status: '',
  student_name: '',
  resume_type: '',
  advisor_id: ''
})

const quickReviewForm = reactive({
  status: 'approved',
  comments: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 方法
const fetchResumeList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filterForm
    }
    
    const response = await resumeApi.getAllResumes(params)
    resumeList.value = response.data.results || []
    pagination.total = response.data.count || 0
  } catch (error) {
    ElMessage.error('获取简历列表失败')
  } finally {
    loading.value = false
  }
}

const fetchStatistics = async () => {
  statisticsLoading.value = true
  try {
    const response = await resumeApi.getReviewStatistics()
    Object.assign(statistics, response.data)
  } catch (error) {
    ElMessage.error('获取统计信息失败')
  } finally {
    statisticsLoading.value = false
  }
}

// 事件处理
const handleSearch = () => {
  pagination.page = 1
  fetchResumeList()
}

const handleReset = () => {
  Object.assign(filterForm, {
    status: '',
    student_name: '',
    resume_type: '',
    advisor_id: ''
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchResumeList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchResumeList()
}

const handleSelectionChange = (selection: any[]) => {
  selectedResumeIds.value = selection.map(item => item.id)
}

const handlePreview = (resume: any) => {
  currentResume.value = resume
  showPreviewDialog.value = true
}

const handleQuickReview = (resume: any) => {
  currentResume.value = resume
  quickReviewForm.status = 'approved'
  quickReviewForm.comments = ''
  showQuickReviewDialog.value = true
}

const confirmQuickReview = async () => {
  if (!quickReviewForm.status) {
    ElMessage.warning('请选择审核结果')
    return
  }

  reviewing.value = true
  try {
    await resumeApi.updateResumeStatus({
      resume_ids: [currentResume.value.id],
      status: quickReviewForm.status,
      comments: quickReviewForm.comments
    })

    ElMessage.success('审核完成')
    showQuickReviewDialog.value = false
    fetchResumeList()
    fetchStatistics()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '审核失败')
  } finally {
    reviewing.value = false
  }
}

const handleBatchUpdate = async (status: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedResumeIds.value.length} 个简历状态更新为 ${getStatusLabel(status)} 吗？`,
      '批量操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await resumeApi.updateResumeStatus({
      resume_ids: selectedResumeIds.value,
      status: status,
      comments: `管理员批量操作：${getStatusLabel(status)}`
    })

    ElMessage.success('批量操作完成')
    selectedResumeIds.value = []
    fetchResumeList()
    fetchStatistics()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败')
    }
  }
}

// 工具函数
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'pending_review': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'needs_revision': 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    'pending_review': '待审核',
    'approved': '已通过',
    'rejected': '未通过',
    'needs_revision': '待修改'
  }
  return labelMap[status] || status
}

// 生命周期
onMounted(() => {
  fetchResumeList()
  fetchStatistics()
})
</script>

<style lang="scss" scoped>
.resume-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }

  .statistics-section {
    margin-bottom: 24px;

    .stat-card {
      text-align: center;
      
      .stat-content {
        .stat-number {
          font-size: 32px;
          font-weight: bold;
          color: var(--color-primary);
        }
        
        .stat-label {
          font-size: 14px;
          color: var(--text-color-secondary);
          margin-top: 8px;
        }
      }

      &.pending .stat-number {
        color: var(--color-warning);
      }

      &.approved .stat-number {
        color: var(--color-success);
      }

      &.rejected .stat-number {
        color: var(--color-danger);
      }
    }
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 20px;
    background: var(--bg-color-light);
    border-radius: 8px;
  }

  .batch-actions {
    margin-bottom: 20px;

    .batch-buttons {
      margin-top: 10px;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>
